#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
区域设置对话框，用于编辑区域参数
"""

from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QGroupBox,
    QLabel, QSpinBox, QPushButton, QCheckBox, QSlider, QLineEdit,
    QColorDialog
)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor

class RegionSettingsDialog(QDialog):
    """区域设置对话框"""

    def __init__(self, rect, parent=None):
        """初始化对话框
        
        参数:
            rect (tuple): 区域坐标 (x, y, w, h)
            parent: 父窗口对象
        """
        super().__init__(parent)
        self.rect = rect
        self.parent = parent
        self.bg_color = [255, 255, 255]  # 默认背景色为白色
        self.bg_threshold = 30  # 默认阈值
        self.enable_bg_removal = False  # 默认不启用背景滤除
        
        # 设置窗口属性
        self.setWindowTitle("区域设置")
        self.setMinimumWidth(400)
        
        # 设置布局
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI界面"""
        layout = QVBoxLayout()
        
        # 显示当前图像文件名
        if hasattr(self.parent, 'region_mgr') and self.parent.region_mgr.current_image_name:
            image_name_label = QLabel(f"当前图像: {self.parent.region_mgr.current_image_name}")
            image_name_label.setStyleSheet("font-weight: bold; color: #0066CC;")
            layout.addWidget(image_name_label)
        
        # 坐标设置分组
        coord_group = QGroupBox("坐标设置")
        coord_layout = QGridLayout()
        
        # X坐标
        coord_layout.addWidget(QLabel("X:"), 0, 0)
        self.x_spinbox = QSpinBox()
        self.x_spinbox.setRange(0, 10000)
        self.x_spinbox.setValue(int(self.rect[0]))  # 转换为整数
        coord_layout.addWidget(self.x_spinbox, 0, 1)
        
        # Y坐标
        coord_layout.addWidget(QLabel("Y:"), 0, 2)
        self.y_spinbox = QSpinBox()
        self.y_spinbox.setRange(0, 10000)
        self.y_spinbox.setValue(int(self.rect[1]))  # 转换为整数
        coord_layout.addWidget(self.y_spinbox, 0, 3)
        
        # 宽度
        coord_layout.addWidget(QLabel("宽度:"), 1, 0)
        self.width_spinbox = QSpinBox()
        self.width_spinbox.setRange(1, 10000)
        self.width_spinbox.setValue(int(self.rect[2]))  # 转换为整数
        coord_layout.addWidget(self.width_spinbox, 1, 1)
        
        # 高度
        coord_layout.addWidget(QLabel("高度:"), 1, 2)
        self.height_spinbox = QSpinBox()
        self.height_spinbox.setRange(1, 10000)
        self.height_spinbox.setValue(int(self.rect[3]))  # 转换为整数
        coord_layout.addWidget(self.height_spinbox, 1, 3)
        
        coord_group.setLayout(coord_layout)
        layout.addWidget(coord_group)
        
        # 背景滤除分组
        bg_group = QGroupBox("背景滤除")
        bg_group.setCheckable(True)
        bg_group.setChecked(self.enable_bg_removal)
        bg_group.toggled.connect(self.on_bg_group_toggled)
        bg_layout = QVBoxLayout()
        
        # 选择背景色
        color_layout = QHBoxLayout()
        color_layout.addWidget(QLabel("背景颜色:"))
        
        # 颜色显示
        self.color_preview = QLabel()
        self.color_preview.setFixedSize(30, 30)
        self.color_preview.setStyleSheet(f"background-color: rgb({self.bg_color[0]}, {self.bg_color[1]}, {self.bg_color[2]}); border: 1px solid black;")
        color_layout.addWidget(self.color_preview)
        
        # 选择颜色按钮
        select_color_btn = QPushButton("选择颜色")
        select_color_btn.clicked.connect(self.on_select_color)
        color_layout.addWidget(select_color_btn)
        
        # 拾取颜色按钮
        pick_color_btn = QPushButton("从图像拾取")
        pick_color_btn.clicked.connect(self.on_pick_color)
        color_layout.addWidget(pick_color_btn)
        
        color_layout.addStretch()
        bg_layout.addLayout(color_layout)
        
        # 颜色阈值滑块
        threshold_layout = QHBoxLayout()
        threshold_layout.addWidget(QLabel("颜色阈值:"))
        
        self.threshold_slider = QSlider(Qt.Horizontal)
        self.threshold_slider.setRange(0, 255)
        self.threshold_slider.setValue(self.bg_threshold)
        self.threshold_slider.setTickPosition(QSlider.TicksBelow)
        self.threshold_slider.setTickInterval(25)
        self.threshold_slider.valueChanged.connect(self.on_threshold_changed)
        threshold_layout.addWidget(self.threshold_slider)
        
        self.threshold_label = QLabel(str(self.bg_threshold))
        threshold_layout.addWidget(self.threshold_label)
        
        bg_layout.addLayout(threshold_layout)
        bg_group.setLayout(bg_layout)
        layout.addWidget(bg_group)
        
        # 按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        ok_button = QPushButton("确定")
        ok_button.clicked.connect(self.accept)
        button_layout.addWidget(ok_button)
        
        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(cancel_button)
        
        layout.addLayout(button_layout)
        
        self.setLayout(layout)
        
    def on_bg_group_toggled(self, checked):
        """背景滤除组切换事件
        
        参数:
            checked (bool): 是否选中
        """
        self.enable_bg_removal = checked
        
    def on_select_color(self):
        """选择颜色事件"""
        color = QColorDialog.getColor(QColor(*self.bg_color), self, "选择背景颜色")
        if color.isValid():
            self.bg_color = [color.red(), color.green(), color.blue()]
            self.update_color_preview()
            
    def on_pick_color(self):
        """从图像拾取颜色事件"""
        # 调用父窗口的颜色拾取功能
        if hasattr(self.parent, 'enable_color_picking'):
            self.parent.enable_color_picking(self)
            self.hide()  # 暂时隐藏对话框
            
    def set_color(self, color):
        """设置颜色
        
        参数:
            color (QColor): 选择的颜色
        """
        if color.isValid():
            self.bg_color = [color.red(), color.green(), color.blue()]
            self.update_color_preview()
            self.show()  # 重新显示对话框
            
    def update_color_preview(self):
        """更新颜色预览"""
        self.color_preview.setStyleSheet(f"background-color: rgb({self.bg_color[0]}, {self.bg_color[1]}, {self.bg_color[2]}); border: 1px solid black;")
            
    def on_threshold_changed(self, value):
        """阈值改变事件
        
        参数:
            value (int): 新的阈值值
        """
        self.bg_threshold = value
        self.threshold_label.setText(str(value))
            
    def get_settings(self):
        """获取设置
        
        返回:
            dict: 区域设置字典
        """
        return {
            "x": self.x_spinbox.value(),
            "y": self.y_spinbox.value(),
            "width": self.width_spinbox.value(),
            "height": self.height_spinbox.value(),
            "enable_bg_removal": self.enable_bg_removal,
            "bg_color": self.bg_color,
            "bg_threshold": self.bg_threshold
        }
    
    def showEvent(self, event):
        """显示事件处理
        
        参数:
            event: 显示事件
        """
        super().showEvent(event)
        
        # 通知主窗口对话框已显示
        if self.parent is not None:
            self.parent.dialog_active = True
            if hasattr(self.parent, 'canvas') and hasattr(self.parent.canvas, 'pause_suggestion'):
                self.parent.canvas.pause_suggestion = True
    
    def closeEvent(self, event):
        """关闭事件处理
        
        参数:
            event: 关闭事件
        """
        # 通知主窗口对话框已关闭
        if self.parent is not None:
            self.parent.dialog_active = False
            if hasattr(self.parent, 'canvas') and hasattr(self.parent.canvas, 'pause_suggestion'):
                self.parent.canvas.pause_suggestion = False
        
        super().closeEvent(event) 